package gxnu.edu.cn.service.impl;

import gxnu.edu.cn.entity.Ccard;
import gxnu.edu.cn.mapper.CcardMapper;
import gxnu.edu.cn.service.CcardService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xwpf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class CcardServiceImpl implements CcardService {

    private final CcardMapper ccardMapper;
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public CcardServiceImpl(CcardMapper ccardMapper) {
        this.ccardMapper = ccardMapper;
    }

    @Override
    public void exportCcards(String fileName, String filePath, String format, List<Ccard> cardList) throws IOException {
        String fullPath = filePath + File.separator + fileName;

        if ("excel".equalsIgnoreCase(format)) {
            try (Workbook workbook = new XSSFWorkbook();
                 FileOutputStream fileOut = new FileOutputStream(fullPath)) {
                Sheet sheet = workbook.createSheet("Ccard Data");

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] headers = {"cardID", "userID", "name", "color", "address", "gender", "status", "cardsId", "createTime", "updateTime"};
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(headers[i]);
                }

                // 填充数据
                int rowNum = 1;
                for (Ccard card : cardList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(card.getCardID());
                    row.createCell(1).setCellValue(card.getUserID());
                    row.createCell(2).setCellValue(card.getName());
                    row.createCell(3).setCellValue(card.getColor());
                    row.createCell(4).setCellValue(card.getAddress());
                    row.createCell(5).setCellValue(card.getGender());
                    row.createCell(6).setCellValue(card.getStatus());
                    row.createCell(7).setCellValue(card.getCardsId());
                    if (card.getCreateTime() != null) {
                        row.createCell(8).setCellValue(card.getCreateTime().format(DATE_TIME_FORMATTER));
                    }
                    if (card.getUpdateTime() != null) {
                        row.createCell(9).setCellValue(card.getUpdateTime().format(DATE_TIME_FORMATTER));
                    }
                }

                workbook.write(fileOut);
            }
        } else if ("word".equalsIgnoreCase(format)) {
            try (XWPFDocument document = new XWPFDocument();
                 FileOutputStream out = new FileOutputStream(fullPath)) {
                // 创建表格
                XWPFTable table = document.createTable();

                // 创建表头
                XWPFTableRow headerRow = table.getRow(0);
                String[] headers = {"cardID", "userID", "name", "color", "address", "gender", "status", "cardsId", "createTime", "updateTime"};
                for (int i = 0; i < headers.length; i++) {
                    if (i > 0) {
                        headerRow.addNewTableCell();
                    }
                    headerRow.getCell(i).setText(headers[i]);
                }

                // 填充数据
                for (Ccard card : cardList) {
                    XWPFTableRow row = table.createRow();
                    row.getCell(0).setText(String.valueOf(card.getCardID()));
                    row.getCell(1).setText(String.valueOf(card.getUserID()));
                    row.getCell(2).setText(card.getName());
                    row.getCell(3).setText(card.getColor());
                    row.getCell(4).setText(card.getAddress());
                    row.getCell(5).setText(card.getGender());
                    row.getCell(6).setText(String.valueOf(card.getStatus()));
                    row.getCell(7).setText(String.valueOf(card.getCardsId()));
                    if (card.getCreateTime() != null) {
                        row.getCell(8).setText(card.getCreateTime().format(DATE_TIME_FORMATTER));
                    }
                    if (card.getUpdateTime() != null) {
                        row.getCell(9).setText(card.getUpdateTime().format(DATE_TIME_FORMATTER));
                    }
                }

                document.write(out);
            }
        } else {
            throw new IllegalArgumentException("不支持的文件格式: " + format);
        }
    }

    @Override
    @Transactional
    public void importCcards(String filePath) throws IOException {
        List<Ccard> cardList = new ArrayList<>();

        if (filePath.endsWith(".xlsx") || filePath.endsWith(".xls")) {
            try (FileInputStream file = new FileInputStream(filePath);
                 Workbook workbook = WorkbookFactory.create(file)) {
                Sheet sheet = workbook.getSheetAt(0);
                boolean isHeader = true;
                for (Row row : sheet) {
                    if (isHeader) {
                        isHeader = false;
                        continue;
                    }
                    Ccard card = new Ccard();
                    card.setCardID((int) row.getCell(0).getNumericCellValue());
                    card.setUserID((int) row.getCell(1).getNumericCellValue());
                    card.setName(row.getCell(2).getStringCellValue());
                    card.setColor(row.getCell(3).getStringCellValue());
                    card.setAddress(row.getCell(4).getStringCellValue());
                    card.setGender(row.getCell(5).getStringCellValue());
                    card.setStatus((int) row.getCell(6).getNumericCellValue());
                    card.setCardsId((int) row.getCell(7).getNumericCellValue());
                    if (row.getCell(8) != null && row.getCell(8).getCellType() == CellType.STRING) {
                        card.setCreateTime(LocalDateTime.parse(row.getCell(8).getStringCellValue(), DATE_TIME_FORMATTER));
                    }
                    if (row.getCell(9) != null && row.getCell(9).getCellType() == CellType.STRING) {
                        card.setUpdateTime(LocalDateTime.parse(row.getCell(9).getStringCellValue(), DATE_TIME_FORMATTER));
                    }
                    cardList.add(card);
                }
            }
        } else {
            throw new IllegalArgumentException("不支持的文件格式: " + filePath);
        }

        if (!cardList.isEmpty()) {
            ccardMapper.batchInsert(cardList);
        }
    }

    @Override
    public List<Ccard> getAllCcards() {
        return ccardMapper.getAllCcards();
    }
}
